﻿/*
 * User: Zachary Gramana
 * Date: 3/31/2011
 * Time: 5:23 PM
 * 
 * Copyright (C) 2011 by Zachary J. Gramana
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.InteropServices;
using System.IO;

namespace SharpScript
{
    /// <summary>
    /// Encapsulates the script and context.
    /// </summary>
    /// <remarks>
    /// We want the ability to run the script inside of
    /// an optional custom AppDomain. We don't want the parent
    /// AppDomain to get polluted with our one-off types.
    /// The runtime context provides a thin wrapper around
    /// the script object to allow management of the child
    /// AppDomain from the parent.  This child domain will
    /// be running with whatever permissions the caller 
    /// decides to grant to the sandbox.
    /// </remarks>
    sealed class RuntimeContext : MarshalByRefObject, IDisposable
    {
        private readonly String         _scriptAssemblyName;
        private readonly ISharpScript   _script;
        private readonly dynamic        _context;
        private          StringWriter   _outputWriter;
        
        public  static   Assembly       ResolveAssembly(object sender, ResolveEventArgs args)
        {
            var commaIndex = args.Name.IndexOf(",", StringComparison.OrdinalIgnoreCase);
            var assemblyName = args.Name.Substring(0, commaIndex);
            
            var assemblyBytes = AppDomain.CurrentDomain.GetData(assemblyName) as byte[];
        	return Assembly.Load(assemblyBytes);
        }
        
        /// <summary>
        /// Creates a new RuntimeContext.
        /// </summary>
        /// <remarks>
        /// The constructor will perform the actual type-instantiation
        /// of our script object, which will then be accessible to
        /// the parent AppDomain.
        /// </remarks>
        /// <param name="host"></param>
        /// <param name="scriptAssembly"></param>
        /// <param name="context"></param>
        public RuntimeContext(String scriptAssemblyName, dynamic context)
        {
            _context = context;
            _scriptAssemblyName = scriptAssemblyName;
            AppDomain.CurrentDomain.AssemblyResolve += ResolveAssembly;
                
            _script = LoadScript();
        }

        public String Run()
        {
            // Redirect console output to a buffer that we
            // can dump into our "output console" control.
            try
            {
                _outputWriter = new StringWriter();
                Console.SetOut(_outputWriter);
            }
            catch (IOException ioe)
            {
                System.Diagnostics.Trace.WriteLine(ioe.Message);
                throw;
            }

            try 
            {
                _script.Run();                
            } 
            catch (Exception ex)
            {    
                throw;
            }
            
            return _outputWriter != null ? _outputWriter.ToString() : null;
        }
        
        private ISharpScript LoadScript()
        {
            Assembly asm = null;
            try
            {
            
                var bytes = AppDomain.CurrentDomain.GetData(_scriptAssemblyName) as byte[];
                asm = Assembly.Load(bytes);
            }
            catch
            {
                throw;
            }

            if (asm == null)
            {
                return null;
            }

            var scriptType = asm.GetType("SharpScript.Script");

            if (scriptType == null)
            {
                return null;
            }

            var results = Activator.CreateInstance(scriptType, new[] {_context}) as ISharpScript;

            return results;
        }

        public void Dispose()
        {
        	_outputWriter.Dispose();
        	System.Diagnostics.Trace.WriteLine("Console StreamWriter was released.");
        }
    }
}
